package groupon.contents.dao.impl;

import groupon.common.dao.impl.GenericDaoImpl;
import groupon.common.util.AppUtil;
import groupon.contents.dao.ContentTypeDao;
import groupon.contents.model.ContentType;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

@Repository(value = "contentTypeDao")
public class ContentTypeDaoImpl extends GenericDaoImpl<ContentType, Integer> implements ContentTypeDao {

	final static Log logger = LogFactory.getLog(ContentTypeDaoImpl.class);
	
	public List<ContentType> getAll() {
		logger.info("----get list content type----");
		return findAll(ContentType.class);
	}
	
	public void save(ContentType contentType){
		persist(contentType);
	}

	public ContentType findContentTypeByName(String name){
			List<Predicate> predicates = new ArrayList<Predicate>();
			CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
			CriteriaQuery<ContentType> criteriaQuery = criteriaBuilder.createQuery(ContentType.class);
			Root<ContentType> from = criteriaQuery.from(ContentType.class);
			criteriaQuery.select(from);
			//check name
			if(!AppUtil.isNullOrEmpty(name)){
				predicates.add(criteriaBuilder.equal(from.get(ContentType.PROP_NAME), name));
			}
			if(predicates.size() == 1){
				criteriaQuery.where(predicates.get(0));
			}else if(predicates.size() > 1){
				criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[0])));
			}
			List<ContentType> listUser = getEntityManager().createQuery(criteriaQuery).getResultList();
			if(!AppUtil.isNullOrEmpty(listUser)){
				return listUser.get(0);
			}
			return null;
		}

	public boolean delete(Integer id) {
		ContentType contentType = findContentType(id);
		logger.info("----get content type>>" + contentType.getId());
		if(contentType != null){
			delete(contentType);
			return true;
		}
		return false;
	}
	
	public ContentType findContentType(Integer id){
		return find(ContentType.class, id);
	}
	
	public ContentType update(ContentType contentType){
		return merge(contentType);
	}
}
